package servlet;

import com.alibaba.fastjson.JSON;
import entity.Employee;
import service.EmployeeServiceDao;
import service.Impl.EmployeeServiceDaoImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@WebServlet("/employee")
public class findEmployeeByName extends HttpServlet {
    private EmployeeServiceDao employeeServiceDao = new EmployeeServiceDaoImpl();
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        resp.setCharacterEncoding("utf-8");
        resp.setContentType("text/html;charset=utf-8");
        String name = req.getParameter("name");
        List<Employee> employeeList;
        if (name != null || !name.isEmpty()) {
            employeeList = employeeServiceDao.findByName(name);
        } else {
            employeeList = employeeServiceDao.findAll();
        }
        //将数据转成json 使用fastjson
        String json = JSON.toJSONString(employeeList);
        //将json数据写给客户端
        resp.getWriter().write(json);
    }
}
